import { Injectable } from '@angular/core';
import { XlsxService } from '@shared/apes/xlsx';
import { SubjectService } from '@core/services/events/subject.service';
import { ApesMessageService } from '@shared/apes/message';

export interface ImportType {
  id: string;
  ctx: any;
  key: any;
  type: any;
  col?: any;
  api?: string;
  name?: string;
}


@Injectable({
  providedIn: 'root',
})
export class ImportService {

  constructor(
    private xlsx: XlsxService,
    private msg: ApesMessageService,
    private subject: SubjectService,
  ) {
  }


  startImportData(param: ImportType) {
    console.log(param);
    switch (param.type) {
      case 'excel':
        this.importExcel(param);
        break;
    }
  }


  private importExcel(param) {
    const item: any = param.ctx['model'][param.key] ? param.ctx['model'][param.key][0] : null;
    if (!item) {
      this.msg.error('请选择导入的文件！');
      return;
    }
    this.xlsx.import(item).then((res) => {
      this.generateExcel(res, param);
    });
  }

  private generateExcel(importData, option) {
    let webTab = [];
    let fieldValue = [];
    let col = option.col;
    let ctx = option.ctx;

    col.forEach((i) => {
      let data = {
        widget: i['cellEditor'],
        api: i['cellEditorParams'],
        name: i['headerName'],
        downFormatter: i['downFormatter'],
        field: i['field'],
      };
      webTab.push(data);
    });

    let data = {
      data: webTab,
      importData: importData,
      fieldkey: option.key,
      fieldValue: fieldValue,
      model: ctx.model,
    };

    this.subject.publish(ctx, this.subject.event_button_callback, data);
  }
}
